package com.life.smile.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.life.smile.entity.RCManagerUser;
import com.life.smile.service.MenuService;


public class SpringMVCInterceptor implements HandlerInterceptor{
	
	@Autowired
	private MenuService menuService;

	
	private static final String[] IGNORE = {"loginOut","code","val","login"};
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURL().toString();
		RCManagerUser user = (RCManagerUser) request.getSession().getAttribute("loginer");
		if (null == user || user.equals("")) {// -----------------------------没有登录(跳转到登录页面)
			for (String s : IGNORE) {// 判断公用页面 公用操作
				if (url.contains(s)) {
					return true;
				}
			}
			response.sendRedirect("/user/loginOut.action");
		}else{
			for (String s : IGNORE) {// 判断公用页面 公用操作
				if (url.contains(s)) {
					return true;
				}
			}
			String[] arr = url.split("/jsp/");
			String authUrl = arr[arr.length-1];
			boolean isAuthor = menuService.searchMenuByUser(user.getUserType(),authUrl);
			if(isAuthor){
				return true;
			}else{
				response.sendRedirect("jsp/error/noPermission.jsp");
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	
}
